const fs = require('fs');
const CryptoJS = require("crypto-js/crypto-js");
const colors = require('colors');
const HTTP = require('../../service/index');
const { API_KEY, API_SECRET, APP_ID, getURCOutput, readOutPutSync } = require('../../config/index');


const API_URL = 'https://ntrans.xfyun.cn/v2/ots';
const HOST = 'ntrans.xfyun.cn';
const POST_URL = '/v2/ots'


/**
 * 获取签名
 * @returns
 */
function getSignature(requestBody) {
    const date = new Date().toUTCString();
    const digest_origin = CryptoJS.enc.Base64.stringify(CryptoJS.SHA256(requestBody));
    const digest = `SHA-256=${digest_origin}`;
    const signature_origin = `host: ${HOST}\ndate: ${date}\nPOST ${POST_URL} HTTP/1.1\ndigest: ${digest}`;

    const signature_sha = CryptoJS.HmacSHA256(signature_origin, API_SECRET)
    return {
        digest,
        date,
        signature: CryptoJS.enc.Base64.stringify(signature_sha)
    }
}

/**
 * 获取鉴权参数
 * @returns
 */
function getAuthorization(requestBody) {
    const { signature, date, digest } = getSignature(requestBody);
    const authorization_origin = `api_key="${API_KEY}",algorithm="hmac-sha256",headers="host date request-line digest",signature="${signature}"`
    return {
        'Content-Type': 'application/json',
        Accept: 'application/json,version=1.0',
        Host: HOST,
        Date: date,
        Digest: digest,
        Authorization: authorization_origin,
    }
}


function getRequestBody(fromLn = 'cn', toLn = 'en', fromText) {
    return {
        "common": {
            "app_id": APP_ID
        },
        "business": {
            "from": fromLn,
            "to": toLn
        },
        "data": {
            "text": CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(fromText))
        }
    }
}

function initTranslation(fromText, fromLn = 'en') {
    if (!fromText) {
        return console.log('未发现可转换文本'.brightRed)
    }
    const data = getRequestBody(fromLn, 'cn', fromText)

    return new Promise((resolve, reject) => {
        HTTP.post(API_URL, data, {
            headers: getAuthorization(data),
        }).then(res => {
            if (res.data) {
                const data = res.data.data;
                resolve(data.result.trans_result.dst)
            }
        }).catch(reject)
    })


}

function init(fromLn = 'en') {
    if (!fromLn) {
        return console.log(`
        请输入待翻译的语言
        语种列表：https://www.xfyun.cn/doc/nlp/niutrans/API.html#语种列表`.brightRed)
    }
    const files = readOutPutSync()
    if (!files || !files.length) {
        return console.log('没有待翻译的文件'.brightRed)
    }
    files.forEach(filePath => {
        const fileTxt = fs.readFileSync(filePath, 'utf8');
        initTranslation(fileTxt, fromLn)
            .then(cn => {
                fs.writeFileSync(filePath, cn)
                console.log(filePath + '----翻译成功'.brightGreen)
            })
            .catch(() => {
                console.log(filePath + '----翻译失败'.brightRed)
            })
    })
}

init(process.argv[2]);